package com.xuecheng.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.system.domain.User;
import com.xuecheng.system.mapper.UserMapper;
import com.xuecheng.system.service.UserService;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService   {
    @Override
    public ResponseResult login(LoginDto loginDto) {
        if (StrUtil.isBlank(loginDto.getUsername()) || StrUtil.isBlank(loginDto.getUtype()) ||StrUtil.isBlank(loginDto.getPassword())){
            ErrorCode code = ErrorCode.PARAMSERROR;
            throw new RuntimeException(code.toString());
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,loginDto.getUsername());
        wrapper.eq(User::getUtype,loginDto.getUtype());
        User one = super.getOne(wrapper);
        if (BeanUtil.isEmpty(one)){
            ErrorCode loginerror = ErrorCode.LOGINERROR;
            throw new BusinessException(loginerror);
        }
        String password = DigestUtil.md5Hex(loginDto.getPassword());
        if (!password.equals(one.getPassword())){
            ErrorCode loginerror = ErrorCode.LOGINERROR;
            throw new BusinessException(loginerror);
        }
        HashMap map = new HashMap();
        map.put("userId",one.getId());
        map.put("companyId",one.getCompanyId());
        map.put("companyName",one.getCompanyName());
        String token = JwtUtils.createToken(map, 180);

        LoginVo vo = new LoginVo();
        vo.setAccess_token(token);
        vo.setUsername(one.getName());
        return ResponseResult.okResult(vo);
    }
}
